﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using xTeam.HengLe.DataAccess;
using System.Web.Mvc;
using xTeam.HengLe.Entity;
using System.ComponentModel;

namespace xTeam.HengLe.Controller.Manage
{
    [Authorize]
    public class AdminController : BaseController
    {
        public AdminController()
        {
            // 数据库连接字符串（BaseController获得）
            AdminDataAccess.Con = _connectionString;
        }

        public ActionResult Index()
        {
            return RedirectToAction("List");
        }

        public ActionResult List()
        {
            List<EAdmin> adminlist = AdminDataAccess.GetByAdminName("");
            return View(adminlist);
        }

        /// <summary>
        /// 根据登录名获取管理员信息
        /// </summary>
        /// <param name="name">登录名</param>
        /// <returns>管理员信息</returns>
        public ActionResult Edit([DefaultValue("")]string name)
        {
            EAdmin admin = new EAdmin() { Isvalid = true }; ;

            if (!string.IsNullOrEmpty(name))
            {
                List<EAdmin> adminList = AdminDataAccess.GetByAdminName(name);

                if (adminList.Count > 0)
                {
                    admin = adminList[0];
                    admin.Password = "";
                }
            }

            return View(admin);
        }

        /// <summary>
        /// 添加和修改管理员
        /// </summary>
        /// <param name="admin">管理员实体</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(EAdmin admin)
        {
            string msg = string.Empty;

            if (string.IsNullOrEmpty(admin.AdminName) || string.IsNullOrEmpty(admin.Password))
            {
                msg = "登录名称或密码不能为空！";
            }
            else
            {
                int ret = AdminDataAccess.Edit(admin);
                
                if (ret > 0)
                {
                    msg = "提交成功！";
                    return Content(string.Format("alert('{0}');location.href='" + Url.Action("List", "Admin") + "';", msg));
                }

                msg = "提交失败！";
            }

            return Content(string.Format("alert('{0}');", msg));
        }
    }
}
